﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Data;
using System.IO;

using EHTSaleManager.Code;
using EHTSaleManager.Code.BLL;
using EHTSaleManager.Code.Utility;
using EHTSaleManager.Code.Entity;

namespace EHTSaleManager.UIAdmin
{
    public partial class AdminCategory : System.Web.UI.Page
    {
        public Int32 categoryID = -1;
        private Int32 parentID = 0;

        private DataTable dtCategorys = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                dtCategorys = CategoryProvider.GetCategorysForBackEnd().Tables[0];

                if (Request.QueryString["CategoryID"] != null)
                {
                    try
                    {
                        categoryID = Int32.Parse(Request.QueryString["CategoryID"].ToString());
                    }
                    catch (Exception ex)
                    {
                        categoryID = -1;
                    }
                }

                if (Request.QueryString["ParentID"] != null)
                {
                    try
                    {
                        parentID = Int32.Parse(Request.QueryString["ParentID"].ToString());
                    }
                    catch (Exception ex)
                    {
                        parentID = 0;
                    }
                }
                
                CreateDDLCategory(0, 0);
                this.ddlCategorys.Items.Insert(0, new ListItem("Top Category", "0"));

                if (categoryID == -1)
                {
                    ViewState["action"] = HangSo.ACTION_ADD;
                    this.ddlCategorys.SelectedValue = parentID.ToString();

                }
                else
                {
                    Category theCategory = CategoryProvider.GetCategoryByCategoryID(categoryID);

                    if (theCategory == null)
                        Response.Redirect("AdminCategorys.aspx");
                    else
                    {
                        this.txtDescription.Text = theCategory.Description;
                        this.txtCategoryName.Text = theCategory.CategoryName;
                        this.ddlCategorys.SelectedValue = theCategory.ParentID.ToString();
                        this.txtOrdering.Text = theCategory.Ordering.ToString();
                        if (theCategory.PictureUrl == null)
                        {
                            this.ImagCategory.ImageUrl = "";
                            ViewState["PictureUrl"] = "";
                        }
                        else
                        {
                            this.ImagCategory.ImageUrl = theCategory.PictureUrl.ToString();
                            ViewState["PictureUrl"] = theCategory.PictureUrl.ToString();
                        }

                        ViewState["ID"] = theCategory.CategoryID;
                        ViewState["action"] = HangSo.ACTION_UPDATE;
                    }
                }
            }
        }

        /// <summary>
        /// Author : toanvt
        /// CreatedDate : 01/02/2012
        /// Description : tạo DropDownList bằng đệ quy
        /// </summary>
        /// <param name="parentID"></param>
        private void CreateDDLCategory(Int32 parentID, Int32 level)
        {
            String preString = "";

            for (Int32 i = 0; i < level; ++i)
            {
                preString += "--";
            }

            DataRow[] drCategorysSub = dtCategorys.Select("ParentID = " + parentID.ToString());
            Int32 amountOfCategorySub = drCategorysSub.Count();

            //Điểm dừng đệ quy
            if (amountOfCategorySub == 0)
                return;

            for (Int32 i = 0; i < amountOfCategorySub; ++i)
            {
                Int32 subCategoryID = Int32.Parse(drCategorysSub[i]["CategoryID"].ToString());

                ListItem li = new ListItem(preString + drCategorysSub[i]["CategoryName"].ToString(), drCategorysSub[i]["CategoryID"].ToString());
                this.ddlCategorys.Items.Add(li);
                CreateDDLCategory(subCategoryID, level + 1);
            }
        }

        private Boolean ValidateData()
        {
            String message = "";
            Boolean isSuccess = true;
            string sExtendsion = ".gif|.GIF|.jpg|.JPG|.png|.PNG";
            try
            {


                if (this.fuPictureUrl.HasFile && sExtendsion.IndexOf(Path.GetExtension(fuPictureUrl.PostedFile.FileName)) < 0)
                {
                    isSuccess = false;
                    message = "Last opp bilde bare.";
                }
            }
            catch (Exception ex)
            {

            }

            if (!isSuccess)
                ltrMessage.Text = message;

            return isSuccess;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            String action = ViewState["action"].ToString();

            if (!ValidateData())
                return;

            Category theCategory = new Category();
            //theCategory.DeletedFlag = this.cbDeletedFlag.Checked;
            theCategory.Description = this.txtDescription.Text.Trim();
            theCategory.CategoryName = this.txtCategoryName.Text;
            try
            {
                theCategory.Ordering = Int32.Parse(txtOrdering.Text);
            }
            catch (Exception ex)
            {
                ltrMessage.Text = "Rekkefølge er ikke numberic";
                return;

            }
            if (Int32.Parse(ddlCategorys.SelectedValue.ToString()) == -1)
            {
                theCategory.ParentID = 0;
            }
            else
            {
                theCategory.ParentID = Int32.Parse(ddlCategorys.SelectedValue.ToString());
            }
            theCategory.Status = true;


            if (this.fuPictureUrl.HasFile)
            {
                String fileName = fuPictureUrl.PostedFile.FileName;
                String fileType = Path.GetExtension(fileName);
                String newFileName = DateTime.Now.Ticks.ToString() + fileType;
                string str = Server.MapPath("~/");
                str += "ImageDatas\\Products\\";
                DirectoryInfo directory = new DirectoryInfo(str);

                if (!directory.Exists)
                {
                    DirectoryInfo drt = new DirectoryInfo("\\ImageDatas");
                    if (!drt.Exists)
                    {
                        directory = new DirectoryInfo(Server.MapPath("~/"));

                        directory = directory.CreateSubdirectory("ImageDatas");

                    }
                    directory = new DirectoryInfo(Server.MapPath("~/").ToString() + "\\ImageDatas");
                    directory = directory.CreateSubdirectory("Products");
                }
                fuPictureUrl.PostedFile.SaveAs(Server.MapPath("~/") + "ImageDatas//Products//" + newFileName);
                theCategory.PictureUrl = "~//ImageDatas//Products//" + newFileName.Trim();
            }
            else
            {
                if (action != HangSo.ACTION_ADD)
                {

                    theCategory.PictureUrl = ViewState["PictureUrl"].ToString();
                }
                else
                {
                    theCategory.PictureUrl = "~//ImageDatas//Products//noImage.gif";
                }


            }

            if (action == HangSo.ACTION_ADD)
            {
                theCategory.CategoryID = -1;
                CategoryProvider.IUCategory(theCategory, true);
            }
            else
            {
                theCategory.CategoryID = Int32.Parse(ViewState["ID"].ToString());
                CategoryProvider.IUCategory(theCategory, false);
            }

            Response.Redirect("AdminCategorys.aspx?CategoryID=" + this.ddlCategorys.SelectedValue);
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("AdminCategorys.aspx?CategoryID=" + Int32.Parse(this.ddlCategorys.SelectedValue.ToString()));
        }

        protected void btnapply_Click(object sender, EventArgs e)
        {
            String action = ViewState["action"].ToString();

            if (!ValidateData())
                return;

            Category theCategory = new Category();
            //theCategory.DeletedFlag = this.cbDeletedFlag.Checked;
            theCategory.Description = this.txtDescription.Text.Trim();
            theCategory.CategoryName = this.txtCategoryName.Text;
            try
            {
                theCategory.Ordering = Int32.Parse(txtOrdering.Text);
            }
            catch (Exception ex)
            {
                ltrMessage.Text = "Rekkefølge er ikke numberic";
                return;

            }
            if (Int32.Parse(ddlCategorys.SelectedValue.ToString()) == -1)
            {
                theCategory.ParentID = 0;
            }
            else
            {
                theCategory.ParentID = Int32.Parse(ddlCategorys.SelectedValue.ToString());
            }
            theCategory.Status = true;


            if (this.fuPictureUrl.HasFile)
            {
                String fileName = fuPictureUrl.PostedFile.FileName;
                String fileType = Path.GetExtension(fileName);
                String newFileName = DateTime.Now.Ticks.ToString() + fileType;
                string str = Server.MapPath("~/");
                str += "ImageDatas\\Products\\";
                DirectoryInfo directory = new DirectoryInfo(str);

                if (!directory.Exists)
                {
                    DirectoryInfo drt = new DirectoryInfo("\\ImageDatas");
                    if (!drt.Exists)
                    {
                        directory = new DirectoryInfo(Server.MapPath("~/"));

                        directory = directory.CreateSubdirectory("ImageDatas");

                    }
                    directory = new DirectoryInfo(Server.MapPath("~/").ToString() + "\\ImageDatas");
                    directory = directory.CreateSubdirectory("Products");
                }
                fuPictureUrl.PostedFile.SaveAs(Server.MapPath("~/") + "ImageDatas//Products//" + newFileName);
                theCategory.PictureUrl = "~//ImageDatas//Products//" + newFileName.Trim();
            }
            else
            {
                if (action != HangSo.ACTION_ADD)
                {

                    theCategory.PictureUrl = ViewState["PictureUrl"].ToString();
                }
                else
                {
                    theCategory.PictureUrl = "~//ImageDatas//Products//noImage.gif";
                }


            }

            if (action == HangSo.ACTION_ADD)
            {
                theCategory.CategoryID = -1;
                CategoryProvider.IUCategory(theCategory, true);
            }
            else
            {
                theCategory.CategoryID = Int32.Parse(ViewState["ID"].ToString());
                CategoryProvider.IUCategory(theCategory, false);
            }
            ltrMessage.Text = "Påfør suksess";
        }
    }

}